package com.poizon.infrastructure.starter.redis;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * @see AbstractRedisUtil
 * Redis工具类
 * lua脚本 缓存穿透 缓存击穿
 */
@Slf4j
public class RedisUtil extends AbstractRedisUtil {
    private static final String LUA_REDIS_HASH_LUA = "lua/redis/hash.lua";
    private static final String HSET_LUA_SCRIPT;

    static {
        try {
            ResourceScriptSource resourceScriptSource = new ResourceScriptSource(new ClassPathResource(LUA_REDIS_HASH_LUA));
            Assert.notNull(resourceScriptSource);
            HSET_LUA_SCRIPT = resourceScriptSource.getScriptAsString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public RedisUtil(StringRedisTemplate redisTemplate) {
        super(redisTemplate);
    }

    @Override
    protected <T> T executeAtomiclyImpl(String luaText, Class<T> clazz, List<String> keys, String[] args, Consumer<T> dealWithReturnValue) {
        DefaultRedisScript<T> redisScript = new DefaultRedisScript<>(luaText, clazz);
        T res = redisTemplate.execute(redisScript, keys, args);
        // 处理返回值
        dealWithReturnValue.accept(res);
        return res;
    }

    @Override
    protected void hSetImpl(String key, String hashKey, Object hashValue, Long time, TimeUnit unit) {
        Assert.notBlank(key);
        Assert.notBlank(hashKey);
        Assert.notNull(time);
        Assert.notNull(unit);

        hashValue = Optional.ofNullable(hashValue).orElse(StrUtil.EMPTY);

        executeAtomiclyImpl(
                HSET_LUA_SCRIPT,
                Long.class,
                Arrays.asList(key, hashKey),
                new String[]{
                        JSON.toJSONString(hashValue),
                        String.valueOf(unit.toMillis(time))
                },
                res -> {
                    log.debug(">hset,res={}", 1);
                });
    }

}
